
package com.kingdee.eas.custom.aoyuan.aytime.bizbill.web;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.ServletRequest;

import org.apache.commons.lang.StringUtils;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.Inject;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.component.form.impl.UIDateField;
import org.operamasks.faces.component.widget.UIButton;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.dao.query.IQueryExecutor;
import com.kingdee.bos.dao.query.QueryExecutorFactory;
import com.kingdee.bos.metadata.MetaDataPK;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.bos.waf.annotation.IBOSBizCtrl;
import com.kingdee.bos.waf.ctx.WafContext;
import com.kingdee.bos.waf.util.OperateState;
import com.kingdee.bos.waf.winlet.edit.EditBean;
import com.kingdee.bos.web.components.widget.impl.UIPromptBox;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.framework.ICoreBase;
import com.kingdee.eas.util.app.ContextUtil;

import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.org.FullOrgUnitInfo;
import com.kingdee.eas.basedata.org.HROrgUnitInfo;
import com.kingdee.eas.basedata.org.PositionInfo;
import com.kingdee.eas.basedata.org.PositionMemberCollection;
import com.kingdee.eas.basedata.org.PositionMemberFactory;
import com.kingdee.eas.basedata.person.Person;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.custom.aoyuan.aytime.AYAttenBillStatusEnum;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.IOTBill;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.OTBillFactory;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.OTBillInfo;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.OTBillEntryInfo;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.OTBillEntryCollection;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.PersonOTBalanceCollection;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.PersonOTBalanceFactory;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.PersonOTBalanceInfo;
import com.kingdee.jdbc.rowset.IRowSet;


@ManagedBean(name = "custom.aoyuan.aytime.bizbill.OTBillEditUIBean", scope = ManagedBeanScope.SESSION)
public class OTBillEditUIBean extends AbstractOTBillEditUIBean {

    @Bind(id="txtBizDate")
    private UIDateField bizDate_label;
    
    @Bind(id="prmtdept")
    private UIPromptBox prmtdept;
    
    @Bind(id="prmtEmp")
    private UIPromptBox prmtEmp;
    
    @Bind(id="prmtposition")
    private UIPromptBox prmtposition;
    
	@Bind	     
	private UIButton btnMySumit;

	@Bind	     
	private UIButton btnMySave;
	
	@Bind
	private PersonOTBalanceInfo otBalanceInfo;
	
	
	public void pageOnload() {
		super.pageOnload();
		
		OTBillInfo modelInfo = (OTBillInfo)this.model;
		FacesContext ctx = FacesContext.getCurrentInstance();
		ServletRequest request = (ServletRequest) ctx.getExternalContext()
		.getRequest();
		
		if (OperateState.ADDNEW.equals(getOperateState())) {
			bizDate_label.setValue(new Date());
			PersonInfo personInfo = ContextUtil.getCurrentUserInfo(
					WafContext.getInstance().getContext()).getPerson();
			newInitF7(personInfo);
		} else if (AYAttenBillStatusEnum.DRAFT.equals(modelInfo.getStatus())) {
			initDeptF7();
			if(OperateState.VIEW.equals(getOperateState()))
			{
				operateState = OperateState.VIEW;	
				btnMySave.setRendered(false);
				btnMySumit.setRendered(false);
			}else
			{
				operateState = OperateState.EDIT;				
			}
		}else if(AYAttenBillStatusEnum.AUDIT_FAIL.equals(modelInfo.getStatus())){
			initDeptF7();
			if(OperateState.VIEW.equals(getOperateState()))
			{
				operateState = OperateState.VIEW;	
				btnMySave.setRendered(false);
				btnMySumit.setRendered(false);
			}else
			{
				operateState = OperateState.EDIT;				
			}
		}else if(AYAttenBillStatusEnum.SUBMIT.equals(modelInfo.getStatus())){
			initDeptF7();
			operateState = OperateState.VIEW;	
			btnMySave.setRendered(false);
			btnMySumit.setRendered(false);		
			String billId = request.getParameter("billId");
			if(StringUtils.isEmpty(billId))
			{
				this.outerScript="alert('该单据已经提交，只能查看!');";				
			}
		}else {
			initDeptF7();
			operateState = OperateState.VIEW;
			btnMySave.setRendered(false);
			btnMySumit.setRendered(false);
			this.outerScript="alert('该单据已经提交，只能查看!');";
		}
		otBalanceInfo=getPersonOTBalanceInfo();
	}
	
	
	
	private PersonOTBalanceInfo getPersonOTBalanceInfo()
	{
		String value = (String) prmtEmp.getSubmittedValue();
		if(StringUtils.isEmpty(value))
		{
			PersonInfo personInfo=(PersonInfo)prmtEmp.getValue();
			if(personInfo!=null)
			{
				value=personInfo.getId().toString();
			}
		}
		
		PersonOTBalanceInfo oTBalanceInfo = null;
		PersonOTBalanceCollection cos=null;
		if(StringUtils.isNotEmpty(value))
		{
			PersonInfo personInfo = new PersonInfo();
			personInfo.setId(BOSUuid.read(value));
			cos = getPersonOTBalanceCollection(personInfo);
		}else
		{
			OTBillInfo modelInfo = (OTBillInfo) this.model;
			PersonInfo personInfo = new PersonInfo();
			if(modelInfo.getEmp()!=null)
			{
				personInfo=modelInfo.getEmp();
			}else
			{
				 personInfo = ContextUtil.getCurrentUserInfo(
						WafContext.getInstance().getContext()).getPerson();
			}

			cos = getPersonOTBalanceCollection(personInfo);
		}
		if (cos != null) {
			if (cos.size() > 0) {
				// 已经存在记录，不创建
				oTBalanceInfo = cos.get(0);
			} else {
				// 新增员工调休记录
				oTBalanceInfo = new PersonOTBalanceInfo();
				oTBalanceInfo.setNormalOT(new BigDecimal("0"));
				oTBalanceInfo.setWeekenOT(new BigDecimal("0"));
				oTBalanceInfo.setHolidayOT(new BigDecimal("0"));
				oTBalanceInfo.setTotaluse(new BigDecimal("0"));
			}
		}else
		{
			// 新增员工调休记录
			oTBalanceInfo = new PersonOTBalanceInfo();
			oTBalanceInfo.setNormalOT(new BigDecimal("0"));
			oTBalanceInfo.setWeekenOT(new BigDecimal("0"));
			oTBalanceInfo.setHolidayOT(new BigDecimal("0"));
			oTBalanceInfo.setTotaluse(new BigDecimal("0"));			
		}			

		return oTBalanceInfo;
	}
	
    private PositionInfo getPosition(PersonInfo personInfo)
    {
		PositionInfo positionInfo = null;
		EntityViewInfo entityViewInfo = new EntityViewInfo();
		FilterInfo filterInfo = new FilterInfo();
		filterInfo.getFilterItems().add(
				new FilterItemInfo("person.id", personInfo.getId(),
						CompareType.EQUALS));
		entityViewInfo.setFilter(filterInfo);
		IQueryExecutor iqec = QueryExecutorFactory.getRemoteInstance(new MetaDataPK(    
                "com.kingdee.eas.custom.aoyuan.aytime.basedata.app",    
                "PersonHRQuery"));
		try {
			iqec.setObjectView(entityViewInfo);  
			IRowSet irow = iqec.executeQuery();
			if(irow.size()>0)
			{
				if(irow.next())
				{
					 positionInfo=new PositionInfo();
					 HROrgUnitInfo hrOrg=new HROrgUnitInfo();
					 AdminOrgUnitInfo adminOrg=new AdminOrgUnitInfo();
					 String positionId=irow.getString("Position.id");
					 String positionName=irow.getString("Position.name");
					 positionInfo.setId(BOSUuid.read(positionId));
					 positionInfo.setName(positionName);
					 String hrOrgId=irow.getString("HROrgUnit.id");
					 String hrOrgName=irow.getString("HROrgUnit.name");
					 hrOrg.setId(BOSUuid.read(hrOrgId));
					 hrOrg.setName(hrOrgName);
					 String adminOrgId=irow.getString("AdminOrgUnit.id");
					 String adminOrgName=irow.getString("AdminOrgUnit.name");
					 adminOrg.setId(BOSUuid.read(adminOrgId));
					 adminOrg.setName(adminOrgName);
					 positionInfo.setAdminOrgUnit(adminOrg);
					 positionInfo.setHrOrgUnit(hrOrg);
				}
			}
/*			PositionMemberCollection coll = PositionMemberFactory
					.getRemoteInstance().getPositionMemberCollection(
							entityViewInfo);
			for (int i = 0; i < coll.size(); i++) {
				if (coll.get(i).getPosition() != null) {
					positionInfo = coll.get(i).getPosition();
					if (positionInfo.getAdminOrgUnit() != null) {
						// 找到对应的岗位和行政组织
						break;
					}
				}
			}*/
			return positionInfo;
		} catch (BOSException e) {
			e.printStackTrace();
			return null;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
    }
	
	private void initDeptF7(){
		OTBillInfo modelInfo=(OTBillInfo)this.model;
		prmtdept.setValue(modelInfo.getDept());
		prmtdept.setSubmittedValue(modelInfo.getDept());
	}
	
	private void newInitF7(PersonInfo personInfo)
	{
		prmtEmp.setValue(personInfo);
		prmtEmp.setSubmittedValue(personInfo.getId().toString());
		PositionInfo positionInfo=getPosition(personInfo);
		OTBillInfo modelInfo=(OTBillInfo)this.model;
		modelInfo.setHROrgUnit(positionInfo.getHrOrgUnit());
		
		prmtposition.setValue(positionInfo);
		prmtposition.setSubmittedValue(positionInfo);
		
		if(positionInfo.getAdminOrgUnit()!=null)
		{
			modelInfo.setDept(positionInfo.getAdminOrgUnit());
			prmtdept.setValue(positionInfo.getAdminOrgUnit());
			prmtdept.setSubmittedValue(positionInfo.getAdminOrgUnit());			
		}
	}
	
	private void getF7Dept()
	{
		Object value = prmtdept.getValue();
		AdminOrgUnitInfo adminOrg=new AdminOrgUnitInfo();
		if(prmtdept.getValue() != null && (!prmtdept.getValue().equals(""))){
			if(value instanceof FullOrgUnitInfo){
				adminOrg.setId(BOSUuid.read(((FullOrgUnitInfo)value).getId().toString()));
				((OTBillInfo) model).setDept(adminOrg);
	         }
		}		
	}
	
	
	public SelectorItemCollection getSelectors() {
		SelectorItemCollection sic = super.getSelectors();
        sic.add(new SelectorItemInfo("id"));
        sic.add(new SelectorItemInfo("*"));
        sic.add(new SelectorItemInfo("creator.*"));
        sic.add(new SelectorItemInfo("entrys.id"));
        sic.add(new SelectorItemInfo("entrys.*"));    
		return sic;
	}
	
	public PersonOTBalanceCollection getPersonOTBalanceCollection(
			PersonInfo personInfo) {

		EntityViewInfo evi = new EntityViewInfo();
		FilterInfo filter = new FilterInfo();
		if (personInfo != null) {
			filter.getFilterItems().add(
					new FilterItemInfo("person.id", personInfo
							.getId().toString(), CompareType.EQUALS));
		} else {
			return null;
		}
		evi.setFilter(filter);
		SelectorItemCollection sic = new SelectorItemCollection();
		sic.add("*");
		evi.setSelector(sic);
		try {
			return PersonOTBalanceFactory.getRemoteInstance()
					.getPersonOTBalanceCollection(evi);
		} catch (BOSException e) {
			e.printStackTrace();
			return null;
		}
	}
	
    public boolean isDisabledByState(String param)
    {
    	boolean isDisabled = true;
    	Map componentRenderMap = new HashMap();  

        if(operateState == null || operateState.equals(OperateState.VIEW) || operateState.equals("amountApproved"))
            componentRenderMap.put("entryRowButton", Boolean.valueOf(true));
        else
            componentRenderMap.put("entryRowButton", Boolean.valueOf(false));
        isDisabled = componentRenderMap.get(param) != null ? ((Boolean)componentRenderMap.get(param)).booleanValue() : true;
        return isDisabled;    	
    }
	
	public void saveModel() {
		getF7Dept();
		OTBillInfo billInfo=(OTBillInfo)model;
		if(!AYAttenBillStatusEnum.AUDIT_FAIL.equals(billInfo.getStatus()))
		{
			billInfo.setStatus(AYAttenBillStatusEnum.DRAFT);			
		}
		super.saveModel();
		this.outerScript="alert('该单据已经保存!');closeWindow();";
	}
	
	public void submitModel() {
		getF7Dept();		
		((OTBillInfo) model).setStatus(AYAttenBillStatusEnum.SUBMIT);
		
		super.submitModel();
	}
}
